<?php

require_once(APPPATH.'controllers/epicentr.php');

class Companies extends Epicentr {

	protected $current_module = "Companies";

	public function Companies() {
		parent::Epicentr();
		$this->view_data['page_js'][] = 'jquery.inplace';
		$this->view_data['page_js'][] = 'companies_inplace';
		
		$this->load->library('validation');
		
		switch ($this->authentication->getProfileType()) {
			case 'admin':
				$this->permissions->addcompany = true;
				$this->permissions->addjob = true;
				$this->permissions->changecompanystatus = true;
				$this->permissions->addcontact = true;
				$this->permissions->addaddress = true;
				$this->permissions->editcontact = true;
				$this->permissions->editaddress = true;
			break;
			case 'standard':
				$this->permissions->addcompany = false;
				$this->permissions->addjob = false;
				$this->permissions->changecompanystatus = false;
				$this->permissions->addcontact = false;
				$this->permissions->addaddress = false;
				$this->permissions->editcontact = false;
				$this->permissions->editaddress = false;
			break;
			case 'client':
				$this->permissions->addcompany = false;
				$this->permissions->addjob = false;
				$this->permissions->changecompanystatus = false;
				$this->permissions->addcontact = true;
				$this->permissions->addaddress = true;
				$this->permissions->editcontact = true;
				$this->permissions->editaddress = true;
			break;
		}
	}
	
	public function index() {
		$this->showClients();
	}
	
	public function all($clients = 0, $prospects = 0, $suppliers = 0, $archived = 0) {
    	if (!$clients && !$prospects && !$suppliers)
    		redirect('companies/clients');
    	
    	$this->load->model('companiesmodel');
    	$this->load->model('usersmodel');
    	
    	$this->view_data['page_js'][] = 'clients';
    	
    	if ($archived === 'archived') $archived = 1;
    	else $archived = 0;
    	
    	$companies = $this->companiesmodel->getCompanyOverview($clients, $prospects, $suppliers, $archived);
		$this->view_data['users'] = $this->usersmodel->find( array('deleted' => 0, 'active' => 1) );
    	
		$user_select = '';
    	if ($this->view_data['users']) {
    		foreach($this->view_data['users'] as $key => $user) {
    			$user_select .= $user->firstname." ".$user->lastname.":".$user->id;
	    		if ($key + 1 < count($this->view_data['users'])) $user_select .= ',';
    		}
    		$this->view_data['user_select'] = $user_select;
    	}
    	
    	if ($companies){
	    	foreach ($companies as $key => $company) {
	    		if ( $this->view_data['company_type'] == 'suppliers' ) $companies[$key]->jobs = $this->companiesmodel->getSuppliersJobs($company->id);
	    		else $companies[$key]->jobs = $this->companiesmodel->getAssociatedJobs($company->id);
	    		
	    		$companies[$key]->contacts = $this->companiesmodel->getAssociatedContacts($company->id);
	    	}
		}
		
		$this->load->model('basemodel');
		$this->basemodel->setModel('industry');
	    $this->view_data['industries'] = $this->basemodel->find( array(), null, null, 'industryname');

		$this->view_data['companies'] = $companies;
		
		$this->view_data['current_uri'] = $this->uri->segment(2);
		$this->view_data['archived'] = $archived;
		
		if ($this->authentication->getProfileType() == 'admin') $this->view_data['addcompany'] = true;
		else $this->view_data['addcompany'] = false;
		
		$this->layout->buildPage('companies/home', $this->view_data);
    }
    
    public function clients($archived = 0) {
    	$this->view_data['view_title'] = "Clients";
    	$this->view_data['maintab'] = 'Clients';
    	$this->view_data['company_type'] = 'clients';
    	$this->all(1, 0, 0, $archived);
    }
    
	public function prospects($archived = 0) {
		$this->view_data['view_title'] = "Prospects";
		$this->view_data['maintab'] = 'Prospects';
		$this->view_data['company_type'] = 'prospects';
    	$this->all(0, 1, 0, $archived);
    }
    
	public function suppliers($archived = 0) {
		$this->view_data['view_title'] = "Suppliers";
		$this->view_data['maintab'] = 'Suppliers';
		$this->view_data['company_type'] = 'suppliers';
    	$this->all(0, 0, 1, $archived);
    }
    
    public function add($company_type = '') {
    	$this->load->model('companiesmodel');
    	$this->load->model('basemodel');
    	
    	$submit = $this->input->post('submit', false);
    	
    	if ($submit) {
    		$company = $this->_get_company_values('add');
    		
    		$companyid = $this->companiesmodel->add($company);
    		
    		$this->db_session->set_flashdata('flashmessage', 'The company was successfully added to the system.');
    		
    		redirect('companies/view/'.$companyid, 'location');
    	} else {
	    	$this->basemodel->setModel('country');
	    	$this->view_data['countries'] = $this->basemodel->find('');
	    	
	    	$this->basemodel->setModel('industry');
	    	$this->view_data['industries'] = $this->basemodel->find('');
	    	
	    	$this->view_data['company_type'] = $company_type;
	    	
	    	$this->view_data['activesection'] = ucfirst($company_type);
	    	
	    	$this->layout->buildPage('companies/add', $this->view_data);
    	}
    }

    public function view($companyid, $archived = 0) {
    	$this->load->model('basemodel');
    	$this->load->model('companiesmodel');
    	$this->load->model('usersmodel');
    	$this->load->model('contactmodel');
    	$this->load->model('jobsmodel');
    	$this->load->model('contactactionmodel');
    	$this->load->model('addressesmodel');
    	
    	$company = $this->companiesmodel->retrieve_by_name($companyid);
		
		if (!$company && intval($companyid))
			$company = $this->companiesmodel->retrieve_by_pkey($companyid);
    	
		if (!$company)
			redirect('companies', 'location');

		$this->view_data['company'] = $company;
		$companyid = $company->id;
    	
    	if ($this->view_data['company'] == false)
			redirect('companies', 'location');
    	
    	$this->view_data['page_js'][] = 'company';
    	
		
		if ($archived === 'archivedjobs') $archived = 1;
    	else $archived = 0;
		
		
		
		//retrieve addresses for this company.
    	$addresses = $this->companiesmodel->getAddresses($companyid);
		$this->view_data['addresslist'] = $this->load->view('epicentr/content/companies/addresslist',array('addresses' => $addresses, 'permissions' => $this->permissions) ,true);

	    
    	//make industry drop down available
		$this->basemodel->setModel('industry');
    	$this->view_data['industries'] = $this->basemodel->find(array(), null, null, 'industryname');
	    if ($this->view_data['industries']) {
	    	$industry_select = '';
	    	foreach($this->view_data['industries'] as $key => $industry) {
	    		$industry_select .= $industry->industryname.":".$industry->id;
	    		if ($key + 1 < count($this->view_data['industries'])) $industry_select .= ',';
	    	}
	    	$this->view_data['industry_select'] = $industry_select;
	    } else  $this->view_data['industry_select'] = "No Industries Availible";
    	
	    
	    //make users dropdown select availible
	    $this->view_data['users'] = $this->usersmodel->find( array('deleted' => 0, 'active' => 1) );
		$user_select = '';
    	if ($this->view_data['users']) {
    		foreach($this->view_data['users'] as $key => $user) {
    			$user_select .= $user->firstname." ".$user->lastname.":".$user->id;
	    		if ($key + 1 < count($this->view_data['users'])) $user_select .= ',';
    		}
    		$this->view_data['user_select'] = $user_select;
    	}
    	
    	//get list of countries.
	    $this->basemodel->setModel('country');
	    $countries = $this->basemodel->find('');
		
		$country_select = '';
    	if ($countries) {
    		foreach($countries as $key => $country) {
    			$country_select .= $country->printable_name.":".$country->id;
	    		if ( $key + 1 < count($countries) )
					$country_select .= ',';
    		}
    		$this->view_data['country_select'] = $country_select;
    	}
	    
	    $this->view_data['countries'] = $countries;
	    
	    //get contacts and their 'actions'
    	$contacts = $this->companiesmodel->getAssociatedContacts($companyid);
    	$this->view_data['contactlist'] = $this->load->view('epicentr/content/companies/contactlist',array('contacts' => $contacts, 'permissions' => $this->permissions) ,true);
    	
    	
    	$this->view_data['contacts'] = $contacts;
    	
		$this->view_data['activejobs'] = $this->companiesmodel->getAssociatedJobs($companyid, 0, 'live');
		
		$this->view_data['proposedjobs'] = $this->companiesmodel->getAssociatedJobs($companyid, 0, 'proposed');
		$this->view_data['completedjobs'] = $this->companiesmodel->getAssociatedJobs($companyid, 0, 'complete');

		$this->view_data['archivedjobs'] = $this->companiesmodel->getAssociatedJobs($companyid, 1); 	

    	
		if ($company->client) $this->view_data['maintab'] = 'Clients';
		else if ($company->prospect) $this->view_data['maintab'] = 'Prospects';
		else if ($company->supplier) $this->view_data['maintab'] = 'Suppliers';

		if ($company->supplier) $supplieron = $this->companiesmodel->getSuppliersJobs($company->id);
		else $supplieron = false;
		
		$this->view_data['supplieron'] = $supplieron;
		
		$this->view_data['archived'] = $archived;

    	$this->layout->buildPage('companies/view', $this->view_data);
    }
    
    //adds a new address to a company
    public function addAddress() {
    	$this->load->model('addressesmodel');
    	
    	$companyid = $this->input->post('companyid');
    	
    	$address = null;
    	$address->datecreated = date('Y-m-d H:i:s');
		$address->creatorid = $this->authentication->getUserId();
  		$address->companyid = $companyid;
   		
   		$addressid = $this->addressesmodel->add($address);
   		
   		$address = $this->addressesmodel->retrieve_by_pkey($addressid);
    	
   		$addresshtml = $this->load->view('epicentr/content/companies/address', array('address' => $address, 'permissions' => $this->permissions), true);
   		
   		include_once ('Zend/Json.php');
		echo Zend_Json::encode( array('status' => 'ok', 'html' => $addresshtml, 'js' => '') );exit();
    }
    
	//delete an address
    public function deleteAddress($addressid = false) {
    	$this->load->model('addressesmodel');
    	
    	if ($addressid) {
    		$address = $this->addressesmodel->retrieve_by_pkey($addressid);
    		
    		$this->addressesmodel->pseudoDelete($addressid);
    	}
    		
    	redirect('companies/view/'.$address->companyid);
    }
        
    public function changeStatus($companyid = 0) {
    	$this->load->model('companiesmodel');
    	
    	$companyid == $this->input->post('companyid');
    	
    	$data = null;
		if ($companyid && $this->input->post('submitval')) {

			$archived = $this->input->post('archived');
			$unarchived = $this->input->post('unarchived');
			$prospect = $this->input->post('prospect');
			$client = $this->input->post('client');
			$supplier = $this->input->post('supplier');

			if ($archived === '1')
				$data->archived = 1;
	
			if ($unarchived === '1')
				$data->archived = 0;
	
			if ($prospect === '1') {
				$data->prospect = 1;
				$data->client = 0;
			}
	
			if ($client === '1') {
				$data->client = 1;
				$data->prospect = 0;
			}
			
			if ($supplier === '1')
				$data->supplier = 1;
				
			if ($supplier === '0')
				$data->supplier = 0;
			
			if ($prospect === '0')
				$data->prospect = 0;

			if ($client === '0')
				$data->client = 0;

			if ($data) $this->companiesmodel->modify($companyid, $data);
		}

		$this->db_session->set_flashdata('flashmessage', 'The company status was updated.');
    		
    	redirect('companies/view/'.$companyid, 'location');
    }
    
    private function _get_company_values($action = null) {
    	$data = null;
    	
    	$data->company_name = $this->input->post('company_name', true);

    	if ($this->input->post('account_code', true))
			$data->account_code = $this->input->post('account_code', true);
			
    	if ($this->input->post('website', true))
			$data->website = $this->input->post('website', true);

		$data->industryid = $this->input->post('industryid', true);

    	$data->retainedclient = $this->input->post('retainedclient', true);
    	
    	$data->prospect = $this->input->post('prospect', true);
    	$data->client = $this->input->post('client', true);
    	$data->supplier = $this->input->post('supplier', true);
    	
    	if ($this->input->post('company_notes', true))
			$data->company_notes = $this->input->post('company_notes', true);
    	
   		if ( $action == 'add') {
			$data->datecreated = date('Y-m-d H:i:s');
			$data->creatorid = $this->authentication->getUserId();
		} else {
			$data->dateupdated = date('Y-m-d H:i:s');
			$data->updaterid = $this->authentication->getUserId();
		}
		
		return $data;
    }
  

}
?>